<template>
  <div class="container-fluid">
    <div class="todos">
      <h3 class="todo-header">Todo示例</h3>
      <create-form @addItem="handleAddItem"></create-form>
      <div v-for="(todo, index) in todoList" :key="index">
        <todo-item
          @deleteTodo="handleDelete"
          @editTodo="handleEdit"
          @editFinish="handleFinish"
          :todo="todo"
          v-if="!todo.isEditable"
        >
        </todo-item>
        <edit-todo :todo="todo" :key="index" @editItem="handleEditTodo" v-else></edit-todo>
      </div>
    </div>
  </div>
</template>

<script setup>
import CreateForm from './CreateForm.vue'
import TodoItem from './Todo.vue'
import EditTodo from './EditTodo.vue'
import { ref } from 'vue'

let todoList = ref([])
// data () {
//   return {
//     todoList: [],
//   }
// }
const handleAddItem = (content) => {
  //console.log(content)
  todoList.value.push({
    id: todoList.value.length + 1,
    content: content,
    isFinished: false,
    isEditable: false,
  })
}
const handleDelete = (id) => {
  const index = todoList.value.findIndex((item) => item, id == id)
  todoList.value.splice(index, 1)
}
const handleEdit = (id) => {
  //找到id：id的todo，修改isEditable为true
  todoList.value.find((todo) => todo.id == id).isEditable = true
}
const handleEditTodo = (id, content) => {
  console.log(id, content)
  //根据id找到todo对象
  const todo = todoList.value.find((todo) => todo.id == id)
  //修改todo内容
  todo.content = content
  //修改isEDITABLE为false
  todo.isEditable = false
}
const handleFinish = (id) => {
  const todo = todoList.value.find((todo) => todo.id == id)
  //当用户点击todo内容时，如果isFinish为false，则修改为true，反之，则修改为false
  todo.isFinished = !todo.isFinished
}
</script>

<style lang="scss" scoped>
.container-fluid {
  width: 100%;
  height: 100vh;
  background: rgb(220, 245, 245);
  display: flex;
  justify-content: center;
  color: rgb(1, 113, 136);
}
.todos {
  width: 450px;
  background-color: rgb(151, 238, 255);
  padding: 20px;
}
.todos > h3 {
  text-align: center;
  margin-top: 20px;
}
</style>
